import React, { Component } from "react";
import { StyleSheet, Animated } from "react-native";
import NetInfo from "@react-native-community/netinfo";

export class OfflineNotice extends Component {
  state = {
    isConnected: true,
    visible: false,
    animated: new Animated.Value(0),
    opacityAnimated: new Animated.Value(0)
  };

  handleConnectivityChange = isConnected => {
    this.setState({ isConnected });
    if (isConnected) {
      this.onEasyOut();
      this.setTimer();
    }
    if (!isConnected) {
      this.onEasyIn();
    }
  };

  setTimer() {
    this.setState({ visible: true });

    if (this._timer != null) {
      clearTimeout(this._timer);
    }

    this._timer = setTimeout(
      function() {
        this.setState({ visible: false });
        this._timer = null;
      }.bind(this),
      800
    );
  }

  componentDidMount() {
    clearTimeout(this._timer);
    NetInfo.isConnected.addEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  }
  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  }

  onEasyIn = () => {
    Animated.parallel([
      Animated.timing(this.state.animated, {
        toValue: 24,
        duration: 600
      }),
      Animated.timing(this.state.opacityAnimated, {
        toValue: 1,
        duration: 500
      })
    ]).start();
  };

  onEasyOut = () => {
    Animated.parallel([
      Animated.timing(this.state.animated, {
        toValue: 0,
        duration: 800
      }),
      Animated.timing(this.state.opacityAnimated, {
        toValue: 0,
        duration: 700
      })
    ]).start();
  };

  render() {
    const animatedHeight = {
      height: this.state.animated
    };
    const opacityAnimated = {
      opacity: this.state.opacityAnimated
    };
    if (!this.state.isConnected) {
      return (
        <Animated.View style={[styles.offlineContainer, animatedHeight]}>
          <Animated.Text style={[styles.offlineText, opacityAnimated]}>
            No Internet Connection
          </Animated.Text>
        </Animated.View>
      );
    }
    if (this.state.visible) {
      return (
        <Animated.View
          style={[
            styles.offlineContainer,
            { backgroundColor: "green" },
            animatedHeight
          ]}
        >
          <Animated.Text style={[styles.offlineText, opacityAnimated]}>
            Back to Online
          </Animated.Text>
        </Animated.View>
      );
    }
    return null;
  }
}

const styles = StyleSheet.create({
  offlineContainer: {
    backgroundColor: "tomato",
    justifyContent: "center",
    alignItems: "center",
    width: "100%"
  },
  offlineText: {
    color: "#fff"
  }
});

export default OfflineNotice;
